package com.pandora.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.pandora.dao.LocationDao;
import com.pandora.dao.impl.LocationDaoImpl;
import com.pandora.entity.LocationEntity;

@SuppressWarnings("serial")
public class LocationServlet extends HttpServlet {

	protected void doGet(HttpServletRequest request, 
			HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, 
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		String action = request.getParameter("action");
		if ("map".equals(action)) {
			maplist(request, response);
		} else {
			list(request, response);
		}
	}

	public void list (HttpServletRequest request, 
			HttpServletResponse response) throws ServletException, IOException {
		LocationDao ld = new LocationDaoImpl();
		List<LocationEntity> list = new ArrayList<LocationEntity>();
		list = ld.getLocationList(Integer.valueOf(request.getParameter("userid")));
		String jsonstr = new Gson().toJson(list);
		System.out.println(jsonstr);
		request.setAttribute("list", list);
		request.getRequestDispatcher("/jsp/list.jsp").forward(request, response);
	}

	public void maplist (HttpServletRequest request, 
			HttpServletResponse response) {
		List<Map<String, Object>> map = new ArrayList<Map<String, Object>>();
		map = new LocationDaoImpl().getAllLocation(Integer.valueOf(request.getParameter("userid")));
		String jsonstr = null;
		jsonstr = new Gson().toJson(map);
		System.out.println(jsonstr);
		printStringxx(request, response, jsonstr);
	}
	
	public void printStringxx(HttpServletRequest request, HttpServletResponse response, String str) {
		PrintWriter out = null;
		try{
			out = response.getWriter();
			out.write(str);
			out.flush();
		} catch(Exception e) {
			System.out.println(e.getMessage());
		} finally {
			if (out != null)
				out.close();
		}
	}
	
}
